<template>
  <!-- 订单列表 -->
  <view class="page-orderList tab-bar-page">
    <topBar :tabTitle="`${getLanguageText('当前', AppSetting.language)} 第${AppSetting.periodsNum}期`"/>
    <flex class="page-nav" direction="column">
      <!-- 期数选择 -->
      <flex style="width: 100%;">
        <span class="expalin">
          {{ getLanguageText('期数', AppSetting.language) }}：
        </span>
        <uni-data-select
          class="search-input"
          v-model="search.periodsNum"
          :localdata="periodsNumRange"
          placeholder="请选择期数"
          @change="periodsNumChange"
        >
        </uni-data-select>
        <!-- 订单状态选择 -->
        <span class="expalin">
          {{ getLanguageText('订单状态', AppSetting.language) }}：
        </span>
        <uni-data-select
          class="search-input"
          v-model="search.status"
          :localdata="statusRange"
          placeholder="请选择状态"
          @change="statusChange"
        >
        </uni-data-select>
      </flex>
      <flex class="key-word-nav">
        <input class="uni-input-search" v-model="search.keyWord" :placeholder="getLanguageText('请输入订单号关键词', AppSetting.language)" maxlength="25" />
        <button 
          class="uni-button key-word-btn" 
          size="mini"  
          type="primary"
          style="border:none;"
          @click="orderListInit"
        >
          {{ getLanguageText('搜索', AppSetting.language) }}
        </button>
      </flex>
    </flex>
    <flex class="page-nav" direction="column" align="flex-start">
      <view class="page-label">
        {{ getLanguageText('订单列表', AppSetting.language) }}: 
      </view>
      <view v-if="!orderList.length" class="explain" style="width: 100%; text-align: center;">
        {{ getLanguageText('暂无数据', AppSetting.language) }}
      </view>
      <template v-else>
        <flex 
          class="orderListItem"
          v-for="(item, index) in orderList" :key="index"
          direction="column" align="flex-start"
          @click.native="myClick('订单详情', {...item, key: index})"
        >
          <flex class="item" justify="space-between">
            <view class="label">{{ getLanguageText('订单编号', AppSetting.language) }}: </view>
            <view>{{ item.id }}</view>
          </flex>
          <flex class="item" justify="space-between">
            <view class="label">{{ getLanguageText('订单总金额', AppSetting.language) }}: </view>
            <view>￥{{ item.money }}</view>
          </flex>
          <flex class="item" align="flex-start">
            <view class="label" style="min-width: 2.8rem;">{{ getLanguageText('下单号码', AppSetting.language) }}: </view>
            <flex class="orderNumList-item" flexWrap="wrap" align="flex-start">
              {{ item.orderNumListStr.toString() }}
            </flex>
          </flex>
          <flex class="item">
            <view class="label">{{ getLanguageText('开奖状态', AppSetting.language) }}： </view>
            <view>{{ item.periodsNumStatus }}</view>
          </flex>
          <flex class="item" justify="space-between">
            <view class="label">{{ getLanguageText('下单时间', AppSetting.language) }}: </view>
            <view>{{ timestampToTime(item.updataTime) }}</view>
          </flex>
          <flex class="item" style="width:100%;" justify="flex-end">
            <button 
              type="warn" 
              size="mini" 
              style="margin: 0;" 
              @click.stop="myClick('作废订单', {...item, key: index})" 
              v-if="!item.del"
            >
              {{ getLanguageText('订单作废', AppSetting.language) }}
            </button>
            <button size="mini" style="margin: 0;" disabled @click.stop="() => {}" v-else>
              {{ getLanguageText('订单已作废', AppSetting.language) }}
            </button>
          </flex>
          <!-- <view>{{ item }}</view> -->
        </flex>
      </template>
    </flex>
    <comTabBar label="列表" />
  </view>
</template>
<script>
import Flex from '../../components/flex/flex.vue';
import { 
  getAppSetting, 
  getOrderList, 
  getOrderSetting,
  setOrderList
} from '../../utils/appStorage'
import {  getLanguageText } from '../../utils/language'

export default {
  name: "orderList",
  data() {
    return {
      AppSetting: {},
      OrderSetting: {},
      search: {
        periodsNum: '',
        status: '',
        keyWord: ''
      },
      orderListBase: [],
      orderListBase2: [],
      // 历史下单数据
      OrderStatisticsList: [],
    };
  },
  components: {Flex},
  onLoad() {
    getAppSetting(data => {
      this.AppSetting = data
      this.search.periodsNum = this.AppSetting.periodsNum
      getOrderSetting(data => {this.OrderSetting = data})
      this.OrderStatisticsInit()
    })
  },
  computed: {
    orderList() {
      let list = []
      for (let i = 0; i < this.orderListBase2.length; i++) {
        const e = this.orderListBase2[i]
        if (!list.find(v => v.id == e.id)) {
          let baseFilter = this.orderListBase2.filter(v => v.id == e.id)
          let money = 0
          let orderNumList = [
            ...e.orderNumTwo,
            ...e.orderNumFour
          ]
          // 计算总金额
          for (let key = 0; key < orderNumList.length; key++) {
            const v = orderNumList[key];
            money += v.quantity * (v.orderNum.length == 4 ? this.OrderSetting.quantityPrice_1 : this.OrderSetting.quantityPrice_2)
          }
          list.push({
            ...e,
            quantityList: baseFilter.map(v => v.quantity),
            money
          })
        }
      }
      return list
    },
    periodsNumRange() {
      let rang = [{
        value: '',
        text: this.getLanguageText('全部', this.AppSetting.language)
      }]
      this.OrderStatisticsList.map((v, i) => {
        rang.push({
          value: v.periodsNum,
          text: `第${v.periodsNum}期`
        })
      })
      return rang
    },
    statusRange() {
      return [{
        value: '',
        text: this.getLanguageText('全部', this.AppSetting.language)
      }, {
        value: 1,
        text: this.getLanguageText('已作废', this.AppSetting.language)
      }]
    },
  },
  methods: {
    orderListInitSetTime() {
      if (
        this.OrderStatisticsList &&
        this.OrderStatisticsList.length
      ) {
        this.orderListInit()
      } else {
        setTimeout(() => {this.orderListInitSetTime()}, 300)
      }
    },
    // 期数数据初始化
    OrderStatisticsInit() {
      // 获取历史数据
      uni.getStorage({
        key: 'OrderStatistics',
        success: (res) => {
          this.OrderStatisticsList = [
            ...this.OrderStatisticsList,
            ...res.data.map(v => {
              return v
            })
          ]
          setTimeout(() => {this.orderListInitSetTime()}, 500)
        }
      })
      // 拼接当前期数数据
      getOrderList(list => {
        let listData = list
        getOrderList(lists => {
          this.OrderStatisticsList.push({
            // 号码维度
            orderList: listData.map(v => {
              return {
                ...v,
                periodsNumStatus: '未开奖',
                periodsNum: this.AppSetting.periodsNum
              }
            }),
            // 订单维度
            orderLists: lists.map(v => {
              return {
                ...v,
                periodsNumStatus: '未开奖',
                periodsNum: this.AppSetting.periodsNum
              }
            }),
            periodsNum: this.AppSetting.periodsNum,
            drawingDate: this.OrderSetting.drawingDate,
            orderAmount: ''
          })
        }, 'OrderLists')
      })
    },
    timestampToTime: (timestamp) => {
      // 时间戳为10位需*1000，时间戳为13位不需乘1000
      let date = new Date(timestamp);
      let Y = date.getFullYear() + "-";
      let M =
        (date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1) + "-";
      let D = (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";
      let h = date.getHours() + ":";
      let m = date.getMinutes() + ":";
      let s = date.getSeconds();
      return Y + M + D + h + m + s;
    },
    getLanguageText,
    // 搜索回调
    periodsNumChange(v) {
      console.log('periodsNumChange-------', v)
      this.search.periodsNum = v
      this.orderListInit()
    },
    statusChange(v) {
      console.log(v)
      this.orderListBase = []
      this.orderListBase2 = []
      this.search.status = v
      this.orderListInit()
    },
    // 订单列表 初始化
    orderListInit() {
      let list = []
      let lists = []
      this.OrderStatisticsList.map(orderStatistics => {
        if (
          !this.search.periodsNum || 
          this.search.periodsNum === orderStatistics.periodsNum
        ) {
          // 号码维度
          list = [
            ...list,
            ...orderStatistics.orderList.map(v => {
              return {
                ...v,
                periodsNumStatus: this.AppSetting.periodsNum != orderStatistics.periodsNum ? '已开奖' : '未开奖',
                periodsNum: orderStatistics.periodsNum
              }
            })
          ]
          // 订单维度
          lists = [
            ...lists,
            ...orderStatistics.orderLists.map(v => {
              return {
                ...v,
                periodsNumStatus: this.AppSetting.periodsNum != orderStatistics.periodsNum ? '已开奖' : '未开奖',
                periodsNum: orderStatistics.periodsNum
              }
            })
          ]
        }
      })
      // 模糊搜索
      if (this.search.keyWord) {
        list = list.filter(orderItem => {
          return (
            orderItem.id.indexOf(this.search.keyWord) !== -1 || 
            orderItem.orderNum.indexOf(this.search.keyWord) !== -1
          )
        })
        lists = list.filter(orderItem => {
          return (
            orderItem.id.indexOf(this.search.keyWord) !== -1
          )
        })
      }
      this.orderListBase = list
      this.orderListBase2 = lists
    },
    myClick(type, data) {
      switch (type) {
        case '作废订单':
          if (data.periodsNum !== this.AppSetting.periodsNum) {
            uni.showToast({title: "旧订单不可作废", icon: 'error'})
            return
          }
          uni.showModal({
            title: "确定作废订单？",
            content: "(该操作不可撤回，请谨慎操作！)",
						confirmText: "确定",
						confirmColor: "#007aff",
						cancelText: "取消",
						cancelColor: "#007aff",
            success: (res) => {
              // console.log('res.confirm------', res.confirm)
              if (res.confirm) {
                // this.orderList.splice(data.key, 1)
                this.orderListBase = this.orderListBase.map(v => {
                  if (v.id === data.id) v.del = 1
                  return v
                })
                this.orderListBase2 = this.orderListBase2.map(v => {
                  if (v.id === data.id) v.del = 1
                  return v
                })
                setOrderList(
                  this.orderListBase, 
                  () => {
                    setOrderList(
                      this.orderListBase2,
                      () => {
                        uni.showToast({title: "作废订单成功", icon: 'success'})
                        setTimeout(() => {
                          uni.redirectTo({ url: '/pages/orderList/orderList' })
                        }, 500)
                      },
                      true,
                      'OrderLists'
                    )
                  }, 
                  true,
                  'OrderList'
                )
              }
            }
          })
          break;
        case '订单详情':
          console.log('data', data)
          if(data.del) {
            uni.showToast({title: "数据已作废", icon: 'error'})
            return
          }
          // return
          uni.navigateTo({
						url: '/pages/orderDetail/orderDetail?query=' + encodeURIComponent(JSON.stringify(data))
					})
          break;
        default:
          break;
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.page-orderList {
  .expalin {
    margin: 0 0 0 0.2rem;
    font-size: 0.7rem;
    color: #747474;
  }
  .search-input + .search-input {
    margin-left: 0.5rem;
  }
  .key-word-nav {
    position: relative;
    width: 100%;
    margin-top: 0.5rem;
  }
  .uni-input-search {
    width: calc(100% - 1rem);
    padding: 0.2rem 0.5rem;
    font-size: 0.7rem;
    border: 1px solid #e5e5e5;
    border-radius: 4px;
  }
  .key-word-btn {
    position: absolute;
    right: 0;
    border-radius: 0 4px 4px 0;
  }
  .orderListItem {
    font-size: 0.6rem;
    margin-top: 0.25rem;
    padding: 0.25rem 0.5rem;
    width: calc(100% - 1rem);
    border: 0.1rem solid #e5e5e5;
    border-radius: 0.3rem;
    .item {
      line-height: 1.6rem;
      .label {
        margin-right: 0.5rem;
      }
    }
    .orderNumList-item {
      margin-right: 0.5rem;
      white-space: normal;
      word-break: break-all;
    }
  }
  .explain {
    color: #747474;
    font-size: 0.7rem;
  }
}
</style>
